<template>
  <div class="workflow-editor">
    <div class="editor-header">
      <el-button @click="handleBack">返回</el-button>
      <el-button 
        v-if="showSaveButton"
        type="primary" 
        @click="handleSave" 
        :loading="saving"
      >{{ processId ? '更新' : '保存' }}</el-button>
    </div>
    <div class="editor-content">
      <div class="editor-container" ref="containerRef"></div>
      <div class="properties-panel-container" id="properties-panel"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import BpmnModeler from 'bpmn-js/lib/Modeler'
import { ElMessage } from 'element-plus'
import { getProcessXML, saveWorkflow, updateWorkflow } from '../../../api/workflow'
import 'bpmn-js/dist/assets/diagram-js.css'
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn.css'
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn-codes.css'
import '@bpmn-io/properties-panel/dist/assets/properties-panel.css'
import '../../../assets/styles/bpmn-properties-panel.css'
import {
  BpmnPropertiesPanelModule,
  BpmnPropertiesProviderModule,
} from 'bpmn-js-properties-panel'

const route = useRoute()
const router = useRouter()
const processId = route.params.id // 从路由参数获取流程ID
const systemId = route.params.systemId as string
const isView = route.path.includes('/view') // 判断是否是查看模式
const isImported = route.query.imported === 'true'

const containerRef = ref<HTMLDivElement>()
const saving = ref(false)
let modeler: BpmnModeler

// 添加中文翻译映射
const translations = {
  'End Event': '结束事件',
  'Exclusive Gateway': '排他网关',
  'Parallel Gateway': '并行网关',
  'Inclusive Gateway': '包容网关',
  'Process': '流程',
  'Create EndEvent': '创建结束事件',
  'Create StartEvent': '创建开始事件',
  'Create Task': '创建任务',
  'Create Gateway': '创建网关',
  'Create DataObjectReference': '创建数据对象',
  'Create DataStoreReference': '创建数据存储',
  'Create exclusive Gateway': '创建排他网关',
  'Create parallel Gateway': '创建并行网关',
  'Create inclusive Gateway': '创建包容网关',
  'Create intermediate/boundary Event': '创建中间/边界事件',
  'Create Pool/Participant': '创建泳池/参与者',
  'Create Lane': '创建泳道',
  'Append EndEvent': '追加结束事件',
  'Append Task': '追加任务',
  'Append Gateway': '追加网关',
  'Append': '追加',
  'Remove': '删除',
  'Activate the hand tool': '激活抓手工具',
  'Activate the lasso tool': '激活套索工具',
  'Activate the create/remove space tool': '激活创建/删除空间工具',
  'Activate the global connect tool': '激活全局连接工具',
  'Create TextAnnotation': '创建文本注释',
  'General': '常规',
  'Details': '详情',
  'Documentation': '文档',
  'Id': '标识',
  'Name': '名称',
  'Process Id': '流程标识',
  'Process Name': '流程名称',
  'Executable': '可执行',
  'Properties': '属性',
  'Property': '属性',
  'Value': '值',
  'Version Tag': '版本标签',
  'Condition': '条件',
  'Flow condition': '流转条件',
  'Assignment': '分配',
  'Assignee': '受理人',
  'Candidate Users': '候选用户',
  'Candidate Groups': '候选组',
  'Due Date': '到期时间',
  'Follow Up Date': '跟进时间',
  'Priority': '优先级',
  'Implementation': '实现',
  'Implementation Type': '实现类型',
  'Expression': '表达式',
  'Delegate Expression': '委托表达式',
  'Script': '脚本',
  'Script Format': '脚本格式',
  'Script Type': '脚本类型',
  'Loop Characteristics': '循环特性',
  'Multi Instance': '多实例',
  'None': '无',
  'Sequential': '串行',
  'Parallel': '并行'
};

// 创建翻译函数
const customTranslate = (template: string, replacements?: Record<string, string>) => {
  // 如果有翻译就返回翻译，没有就返回原文
  return translations[template] || template;
};

// 创建翻译模块
const customTranslateModule = {
  translate: ['value', customTranslate]
};

// 初始化BPMN建模器
onMounted(async () => {
  if (!containerRef.value) return

  modeler = new BpmnModeler({
    container: containerRef.value,
    propertiesPanel: {
      parent: '#properties-panel'
    },
    additionalModules: [
      BpmnPropertiesPanelModule,
      BpmnPropertiesProviderModule,
      customTranslateModule
    ],
    // 如果是查看模式，禁用键盘事件
    if (isView) {
      const keyboard = modeler.get('keyboard')
      keyboard.bind(null) // 禁用键盘事件
    }
  })

  // 如果是导入模式，从sessionStorage获取XML
  if (isImported) {
    const importedXML = sessionStorage.getItem('importedBpmnXML')
    if (importedXML) {
      try {
        await modeler.importXML(importedXML)
        // 清除sessionStorage
        sessionStorage.removeItem('importedBpmnXML')
      } catch (error) {
        console.error('导入的XML解析失败:', error)
        ElMessage.error('导入的文件格式不正确')
        await modeler.createDiagram()
      }
    }
  } else if (processId) {
    // 加载已有流程
    await loadExistingProcess()
  } else {
    // 创建新图表
    await modeler.createDiagram()
  }
})

// 清理资源
onUnmounted(() => {
  modeler?.destroy()
})

// 组件销毁时清理storage
onUnmounted(() => {
  sessionStorage.removeItem('importedBpmnXML')
})

// 返回列表页
const handleBack = () => {
  router.back()
}

// 保存流程
const handleSave = async () => {
  try {
    saving.value = true
    
    // 获取XML
    const { xml } = await modeler.saveXML({ format: true })
    
    // 获取流程定义的基本信息
    const rootElement = modeler.get('canvas').getRootElement()
    const businessObject = rootElement.businessObject
    const processName = businessObject.name || ''
    const processKey = businessObject.id || ''
    
    // 创建FormData
    const formData = new FormData()
    formData.append('file', new Blob([xml], { type: 'text/xml' }), 'process.bpmn')
    formData.append('systemId', systemId)
    formData.append('name', processName)
    formData.append('key', processKey)
    
    // 根据是否有processId判断是新建还是更新
    if (processId) {
      await updateWorkflow(Number(processId), formData)
      ElMessage.success('更新成功')
    } else {
      await saveWorkflow(formData)
      ElMessage.success('保存成功')
    }
    
    router.back()
  } catch (error: any) {
    ElMessage.error(error.message || '保存失败')
  } finally {
    saving.value = false
  }
}

// 加载已有流程
const loadExistingProcess = async () => {
  try {
    if (!processId) return
    
    const res = await getProcessXML(Number(processId))
    const { xml } = res.data
    
    // 导入现有的 XML
    await modeler.importXML(xml)
    
    // 如果是查看模式，禁用编辑
    if (isView) {
      // 禁用编辑功能
      const canvas = modeler.get('canvas')
      canvas.viewbox(canvas.viewbox())
      
      // 禁用工具栏和右键菜单
      const elementRegistry = modeler.get('elementRegistry')
      const elements = elementRegistry.getAll()
      elements.forEach(element => {
        const gfx = elementRegistry.getGraphics(element)
        if (gfx) {
          gfx.style.pointerEvents = 'none'
        }
      })
      
      // 隐藏工具栏
      const palette = modeler.get('palette')
      palette.close()
    }
  } catch (error) {
    console.error('加载流程失败:', error)
    ElMessage.error('加载流程失败')
  }
}

// 显示保存按钮的条件：不是查看模式
const showSaveButton = computed(() => !isView)
</script>

<style scoped>
.workflow-editor {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.editor-header {
  padding: 8px;
  border-bottom: 1px solid #dcdfe6;
  display: flex;
  gap: 8px;
}

.editor-content {
  flex: 1;
  display: flex;
  background-color: #fff;
}

.editor-container {
  flex: 1;
  background-color: #fff;
}

.properties-panel-container {
  width: 300px;
  border-left: 1px solid #dcdfe6;
  overflow-y: auto;
}

:deep(.bjs-powered-by) {
  display: none;
}

:deep(.djs-palette) {
  background: #fff;
  border-right: 1px solid #dcdfe6;
}
</style>